// pages/dashboard/sumdetails/index.js
const app = getApp();
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		role: '',
		scrollList: [],
		valuedetail: '',
		maxDate: new Date().setFullYear(new Date().getFullYear() + 2),
		date: '2020-10-10 至 2020-10-11',
		show: false,
		minDate: new Date(2021, 6, 1).getTime(),
		maxDate: new Date().getTime(),
		list: [
			{ name: '货主交易', id: 1 },
			{ name: '农户交易', id: 2 }
		],
		activeIndex: null,
		active: 1,
		personList: [],
		// farmers: [],
		value: '',//搜索值,
		tableDate: {},
		userId: '',
		countWeightTotal: "",
		countTotal: "",
		turnoverTotal: "",
		 mobile:'',
			cropId:null
	},

	getrow(e) {
		const name = e.currentTarget.dataset.name;
		const userId = e.currentTarget.dataset.userid;
		const active = this.data.active;
		const mobile = wx.$getMobile(e.currentTarget.dataset.mobile);
		wx.navigateTo({
			url: "/pages/dashboard/analysis/analysis?userId=" + userId + "&name=" + name + "&type=" + active + "&mobile=" + mobile
		});

	},
	//搜索
	onSearch(e) {
		this.setData({
			value: e.detail
		})
		console.log('搜索', this.data.value)
		if (this.data.active == 1) {
			this.getInfo(true)
		} else {
			this.getInfo(false)
		}
	},
	handle(e) {
		console.log(e)
		let id = e.currentTarget.dataset.id
		this.setData({
			active: id,
			value: ''
		})
		if (id == 1) {
			this.getInfo(true)
		} else {
			this.getInfo(false)
		}
	},
	onDisplay() {
		this.setData({ show: true });
	},
	onClose() {
		this.setData({ show: false });
	},
	formatDate(date) {
		date = new Date(date);
		var Y = date.getFullYear();
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
		return `${Y}-${M}-${D}`;
	},
	onConfirm(event) {
		const [start, end] = event.detail;
		this.setData({
			show: false,
			date: `${this.formatDate(start)}至${this.formatDate(end)}`,
		});
		if(this.formatDate(end)===this.formatDate(start)){
			this.setData({
				onLage:2,
				singleTime:this.data.date.split('至')[0]
			})
		}else{
			this.setData({
				onLage:1
			})
		}
		this.getFee();

	},
	scroll(e) {
	},
	handlescroll(e) {
		// console.log(e)
		this.setData({
			activeIndex: e.currentTarget.dataset.id,
			cropId: e.currentTarget.dataset.id*1,
		})
		this.getSevenDay();
		this.getFee();
	},
	
	//获取近7天时间---获取当天
	getSevenDay() {
		var timestamp = Date.parse(new Date());
		timestamp = timestamp / 1000;
		var date = new Date(timestamp * 1000);
		//获取年份
		var Y = date.getFullYear();
		//获取月份
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		//获取当日日期
		var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
		//减7天的时间戳：
		var before_timetamp = timestamp - 24 * 60 * 60 * 6;
		//減7天的时间：
		var n_to = before_timetamp * 1000;
		var before_timetamp = new Date(n_to);
		var Y_before = before_timetamp.getFullYear();
		//月份
		var M_before = (before_timetamp.getMonth() + 1 < 10 ? '0' + (before_timetamp.getMonth() + 1) : before_timetamp.getMonth() + 1);
		//日期
		var D_before = before_timetamp.getDate() < 10 ? '0' + before_timetamp.getDate() : before_timetamp.getDate();
		// this.setData({
		// 	date: `${Y_before}-${M_before}-${D_before}至${Y}-${M}-${D}`
		// })
		this.setData({
			onLage:2,
			date: `${Y}-${M}-${D}至${Y}-${M}-${D}`,
			singleTime:`${Y}-${M}-${D}`,
})
	},
	//获取作物信息
	getCrops() {
		if (this.data.role == 1) {
      let companyId = app.globalData.userInfo.companyData.companyId;
			wx.$apis.marketCrops(companyId).then(res => {
				// wx.hideLoading()
				res.data.forEach(item=>{
					item.cropName=item.name
				})
				this.setData({
					scrollList: res.data,
					activeIndex: res.data[0].id,
					cropId: res.data[0].id*1,
				})
				this.getFee();
			}).catch(err => {
				wx.hideLoading()
			})
		} else if (this.data.role == 2) {
			//getFarmerCrops
			wx.$apis.getFarmerCrops().then(res => {
				var newArr = res.data.map(item => ({
					cropName: item.name,
					id: item.id
				}))
				// wx.hideLoading()
				this.setData({
					scrollList: newArr,
					activeIndex: newArr[0].id,
					cropId: res.data[0].id*1,
				})
				this.getFee();
			}).catch(err => {
				wx.hideLoading()
			})
		}
	},
	//费用详情 
	getFee() {
		var parmas = {
			companyId: app.globalData.userInfo.companyData.companyId,
			startTime: this.data.date.split('至')[0] + " 00:00:00",
			endTime: this.data.date.split('至')[1] + " 23:59:59",
			cropId: this.data.activeIndex
		}
		let api;
		if (this.data.role == 1) {
			api = "detailCount"
		} else {
			api = "countDetail"
		}
		wx.$apis[api](parmas).then(res => {
			var data = res.data;
			// var list = this.data.financialList.map(item => {
			//   return {
			//     name: item.name,
			//     count: data[item.key] ? data[item.key] : 0
			//   }
			// });
			this.setData({
				// financialList: list,
				tableDate: data
			})
		}).catch(err => {
			wx.hideLoading()
		})
	},
	//农户货主信息    
	getInfo(item) {
		var parmas = {
			companyId: app.globalData.userInfo.companyData.companyId,
			name: this.data.value,
			qw: item,//货主true
		}
		wx.$apis.tradeOrderCount(parmas).then(res => {
			var data = res.data;
			// var list = this.data.financialList.map(item => {
			//   return {
			//     name: item.name,
			//     count: data[item.key] ? data[item.key] : 0
			//   }
			// });
			this.setData({
				personList: data.map((item) => {
					return {
						...item,
						turnover: wx.$getYuan(item.turnover)
					};
				})
			})

			var countWeightTotal = this.data.personList.reduce((acc, cur) => {
				return acc + cur.countWeight
			}, 0)
			var countTotal = this.data.personList.reduce((acc, cur) => {
				return acc + cur.count
			}, 0)
			var turnoverTotal = this.data.personList.reduce((acc, cur) => {
				return acc + cur.turnover
			}, 0)
			this.setData({
				countWeightTotal,
				countTotal,
				turnoverTotal
			})
		}).catch(err => {
			wx.hideLoading()
		})
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.setData({
			role: app.globalData.userInfo.role,
		})
		this.getCrops();
		this.getSevenDay();
		if (this.data.role == 1) {
			this.getInfo(true);
		} else {
			this.setData({
				userId: app.globalData.userInfo.userDetail.id,
			})
			// console.log(app.globalData.userInfo.userDetail.id, 'app.globalData.userInfo.userId')
		}
		console.log('角色', this.data.role)
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})